package service

import (
	"context"
	"fmt"
	__ "order_srv/basic/orderproto"
	"order_srv/handler/dao"
)

// Server 订单服务实现
// 这里已经有Server结构体的定义，所以我们直接添加方法

// 按日统计订单数据
func (s *Server) OrderStatistics(_ context.Context, in *__.OrderStatisticsReq) (*__.OrderStatisticsResp, error) {
	var res, err = dao.CountOrdersBySpecificDay(in.Data, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	return &__.OrderStatisticsResp{
		OrderDate:         res.OrderDate,
		TotalOrderCount:   res.TotalOrderCount,
		UnpaidOrderCount:  res.UnpaidOrderCount,
		InvalidOrderCount: res.InvalidOrderCount,
		ValidOrderCount:   res.ValidOrderCount,
		RefundOrderCount:  res.RefundOrderCount,
	}, nil
}

// 按周统计订单数据
func (s *Server) WeekOrderStatistics(_ context.Context, in *__.WeekOrderStatisticsReq) (*__.WeekOrderStatisticsResp, error) {
	res, err := dao.GetChartOrderData(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	var list []*__.OrderStatisticsList
	for _, v := range res {
		list = append(list, &__.OrderStatisticsList{
			OrderDate:         v.OrderDate,
			TotalOrderCount:   v.TotalOrderCount,
			UnpaidOrderCount:  v.UnpaidOrderCount,
			InvalidOrderCount: v.InvalidOrderCount,
			ValidOrderCount:   v.ValidOrderCount,
			RefundOrderCount:  v.RefundOrderCount,
		})
	}
	return &__.WeekOrderStatisticsResp{
		List: list,
	}, nil
}

// 按月统计订单数据
func (s *Server) MonthOrderStatistics(_ context.Context, in *__.MonthOrderStatisticsReq) (*__.MonthOrderStatisticsResp, error) {
	res, err := dao.GetMonthlyOrderData(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	var list []*__.OrderStatisticsList
	for _, v := range res {
		list = append(list, &__.OrderStatisticsList{
			OrderDate:         v.OrderDate,
			TotalOrderCount:   v.TotalOrderCount,
			UnpaidOrderCount:  v.UnpaidOrderCount,
			InvalidOrderCount: v.InvalidOrderCount,
			ValidOrderCount:   v.ValidOrderCount,
			RefundOrderCount:  v.RefundOrderCount,
		})
	}
	return &__.MonthOrderStatisticsResp{
		List: list,
	}, nil
}

// 按年统计订单数据
func (s *Server) YearOrderStatistics(_ context.Context, in *__.YearOrderStatisticsReq) (*__.YearOrderStatisticsResp, error) {
	res, err := dao.GetYearlyOrderData(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	var list []*__.OrderStatisticsList
	for _, v := range res {
		list = append(list, &__.OrderStatisticsList{
			OrderDate:         v.OrderDate,
			TotalOrderCount:   v.TotalOrderCount,
			UnpaidOrderCount:  v.UnpaidOrderCount,
			InvalidOrderCount: v.InvalidOrderCount,
			ValidOrderCount:   v.ValidOrderCount,
			RefundOrderCount:  v.RefundOrderCount,
		})
	}
	return &__.YearOrderStatisticsResp{
		List: list,
	}, nil
}

// 返回某天订单平均金额
func (s *Server) DateAverageOrderAmount(_ context.Context, in *__.DateAverageOrderAmountReq) (*__.DateAverageOrderAmountResp, error) {
	res, err := dao.GetDayAvgAmount(in.Date, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	return &__.DateAverageOrderAmountResp{
		AvgPrice:   float32(res.AvgAmount),
		Date:       res.Date,
		OrderCount: int64(res.OrderCount),
	}, nil
}

// 获取范围内日数据平均金额
func (s *Server) DateBetweenAverageOrderAmount(_ context.Context, in *__.DateBetweenAverageOrderAmountReq) (*__.DateBetweenAverageOrderAmountResp, error) {
	res, err := dao.CalculateRangeAvgAmount(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	var list []*__.AvgOrderPriceList
	for _, v := range res {
		l := __.AvgOrderPriceList{
			AvgPrice:   float32(v.AvgAmount),
			Date:       v.Date,
			OrderCount: int64(v.OrderCount),
		}

		list = append(list, &l)
	}
	return &__.DateBetweenAverageOrderAmountResp{
		List: list,
	}, nil
}

// 按月统计订单平均价
func (s *Server) MonthOrderAvgPrice(_ context.Context, in *__.MonthOrderAvgPriceReq) (*__.MonthOrderAvgPriceResp, error) {
	res, err := dao.GetAvgPriceByMonth(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	var list []*__.AvgOrderPriceList
	for _, v := range res {
		l := __.AvgOrderPriceList{
			AvgPrice:   float32(v.AvgAmount),
			Date:       v.Date,
			OrderCount: int64(v.OrderCount),
		}

		list = append(list, &l)
	}
	return &__.MonthOrderAvgPriceResp{
		List: list,
	}, nil
}

// 按年获取订单平均价
func (s *Server) YearAverageOrderAmount(_ context.Context, in *__.YearAverageOrderAmountReq) (*__.YearAverageOrderAmountResp, error) {
	res, err := dao.GetAvgPriceByYear(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	fmt.Println(res)
	var list []*__.AvgOrderPriceList
	for _, v := range res {
		l := __.AvgOrderPriceList{
			AvgPrice:   float32(v.AvgAmount),
			Date:       v.Date,
			OrderCount: int64(v.OrderCount),
		}

		list = append(list, &l)
	}
	return &__.YearAverageOrderAmountResp{
		List: list,
	}, nil
}

// 按周统计订单平均价
func (s *Server) WeekAverageOrderAmount(_ context.Context, in *__.WeekAverageOrderAmountReq) (*__.WeekAverageOrderAmountResp, error) {
	res, err := dao.GetAvgPriceByWeek(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}
	var list []*__.AvgOrderPriceList
	for _, v := range res {
		l := __.AvgOrderPriceList{
			AvgPrice:   float32(v.AvgAmount),
			Date:       v.Date,
			OrderCount: int64(v.OrderCount),
		}

		list = append(list, &l)
	}
	return &__.WeekAverageOrderAmountResp{
			List: list,
		},
		nil
}

// OrderGrowthRate 计算订单增长率，每两小时一组
func (s *Server) OrderGrowthRate(_ context.Context, in *__.OrderGrowthRateReq) (*__.OrderGrowthRateResp, error) {
	// 直接使用传入的日期调用GetTwoHourOrderCounts函数
	res, err := dao.GetTwoHourOrderCounts(in.Date, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}

	var list []*__.OrderGrowthRateList

	// 计算增长率
	for i := 0; i < len(res); i++ {
		growthRateItem := &__.OrderGrowthRateList{
			TimeSlot:     res[i].TimeSlot,
			CurrentCount: res[i].OrderCount,
		}

		// 对于第一个时间段，没有上一个时间段的数据，增长率为0
		if i > 0 {
			growthRateItem.PreviousCount = res[i-1].OrderCount

			// 计算增长率
			if res[i-1].OrderCount > 0 {
				growthRateItem.GrowthRate = float32((res[i].OrderCount - res[i-1].OrderCount) * 100 / res[i-1].OrderCount)
			} else if res[i].OrderCount > 0 {
				// 如果上一个时间段没有订单，但当前时间段有订单，则增长率为100%
				growthRateItem.GrowthRate = 100
			} else {
				// 如果两个时间段都没有订单，则增长率为0
				growthRateItem.GrowthRate = 0
			}
		} else {
			growthRateItem.PreviousCount = 0
			growthRateItem.GrowthRate = 0
		}

		list = append(list, growthRateItem)
	}

	return &__.OrderGrowthRateResp{
			List: list,
		},
		nil
}

// GetRepurchaseByInterval 按时间间隔统计复购人数
func (s *Server) GetRepurchaseByInterval(_ context.Context, in *__.GetRepurchaseByIntervalReq) (*__.GetRepurchaseByIntervalResp, error) {
	// 调用DAO层函数获取按时间间隔统计的复购人数数据
	res, err := dao.GetRepurchaseByInterval(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}

	var list []*__.RepurchaseIntervalItem
	for _, v := range res {
		intervalItem := &__.RepurchaseIntervalItem{
			Interval: v.Interval,
			Count:    v.Count,
		}
		list = append(list, intervalItem)
	}

	return &__.GetRepurchaseByIntervalResp{
		List: list,
	}, nil
}

// GetPurchaseConversion 购买转化分析统计
func (s *Server) GetPurchaseConversion(_ context.Context, in *__.GetPurchaseConversionReq) (*__.GetPurchaseConversionResp, error) {
	// 调用DAO层函数获取购买转化分析数据
	res, err := dao.GetPurchaseConversionData(in.StartTime, in.EndTime, in.OrderType, in.PayWay)
	if err != nil {
		return nil, err
	}

	// 转换数据格式
	var list []*__.PurchaseConversionData
	for _, v := range res {
		conversionData := &__.PurchaseConversionData{
			Date:               v.Date,
			NewUserCount:       v.NewUserCount,
			ConvertedUserCount: v.ConvertedUserCount,
			ConversionRate:     float32(v.ConversionRate),
		}
		list = append(list, conversionData)
	}

	return &__.GetPurchaseConversionResp{
		List: list,
	}, nil
}
